package controler;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.ConnectionFabric;
import model.Vendas;

/**
 * Servlet implementation class ServletTroca
 */
@WebServlet("/ServletTroca")
public class ServletTroca extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletTroca() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
	int codigo = Integer.parseInt(request.getParameter("codigo"));

	
	String sql = "select v.cod_Venda as Cupom, v.Data, c.nome as Cliente, v.valorvenda as Total, f.nome as Vendedor from venda as v " +
			"INNER JOIN clientes as c ON v.Cliente_idCLiente = c.idCliente INNER JOIN funcionario as f " +
			"ON v.funcionario_idfuncionario = f.idfuncionario WHERE v.cod_Venda = ?";

	    try{
	    	
		    Connection con = ConnectionFabric.getConnection();	    	
		    PreparedStatement ps = con.prepareStatement(sql);
		    ps.setInt(1,codigo); 
		    ResultSet rs = ps.executeQuery();	
		    
		    List<Vendas> lista = new ArrayList<Vendas>();
		    while(rs.next()){
		    Vendas vend = new Vendas();
		    vend.setId_venda(rs.getInt("Cupom"));
		    vend.setData(rs.getDate("data"));
		    vend.setValorvenda(rs.getDouble("Total"));
		    vend.setFunc(rs.getString("Vendedor"));
		    vend.setCli(rs.getString("Cliente"));  
		    
		    lista.add(vend);
		    }
		    
		    
		    HttpSession sessao = request.getSession();
		    sessao.setAttribute("list",lista);  
		    RequestDispatcher rd = request.getRequestDispatcher("troca.jsp");  
		    rd.forward(request, response); 
		    }catch(Exception ex){	    	
		    	ex.printStackTrace();	
		                        }	
	    
	    
                                   } 
	
                 	}
	